package com.tjetc.dao.impl;

import com.tjetc.dao.RoomDao;
import com.tjetc.pojo.dto.CheckInDTO;
import com.tjetc.pojo.entity.Room;
import com.tjetc.utils.DruidUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * @Author: itda
 * @Date: 2024/5/10 18:46
 * @Description: RoomDaoImpl
 */
public class RoomDaoImpl implements RoomDao {
    @Override
    public void save(Room room) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "insert into room (hotel_id, type, price, capacity, description, availability) " +
                "values (?,?,?,?,?,?)", room.getHotelId(), room.getType(), room.getPrice(), room.getCapacity(), room.getDescription(), room.getAvailability());
    }

    @Override
    public void deleteById(Long id) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "delete from room where id = ?", id);
    }

    @Override
    public void update(Room room) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "update room set hotel_id = ?,type = ?,price = ?,capacity = ?,description = ?,availability = ? where id = ?"
                , room.getHotelId(), room.getType(), room.getPrice(), room.getCapacity(), room.getDescription(), room.getAvailability(), room.getId());
    }

    @Override
    public List<Room> list() throws Exception {
        return DruidUtils.r2.query("select * from room", new BeanListHandler<>(Room.class, DruidUtils.rowProcessor));
    }

    @Override
    public Room getById(Long id) throws Exception {
        return DruidUtils.r2.query("select * from room where id = ?", new BeanHandler<>(Room.class, DruidUtils.rowProcessor), id);
    }

    @Override
    public void deleteByHotelId(Long hotelId) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "delete from room where hotel_id = ?", hotelId);
    }

    @Override
    public List<Room> getByStatus(int status) throws Exception {
        return DruidUtils.r2.query("select * from room where availability = ?", new BeanListHandler<>(Room.class, DruidUtils.rowProcessor), status);
    }

    @Override
    public void updateStatusById(Long roomId, Short availability) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "update room set availability = ? where id = ?",
                availability==4?1:++availability, roomId);
    }

    @Override
    public void checkIn(CheckInDTO checkInDTO) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "update room set availability = ? where hotel_id = ? and id = ?", 3, checkInDTO.getHotelId(), checkInDTO.getRoomId());
    }
}
